package cn.ycq.im.service;

import cn.ycq.im.commons.exceptions.ServiceException;
import cn.ycq.im.commons.utils.JwtUtis;
import cn.ycq.im.mapper.UserMapper;
import cn.ycq.im.model.User;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public String login(String email) {
        User query = new User();
        query.setEmail(email);
        User user = userMapper.selectOne(new QueryWrapper<User>(query));

        Long userId;
        if(user == null){
            query.setCreateTime(new Date());
            query.setUpdateTime(new Date());
            query.setDel(0);
            userMapper.insert(query);
            userId = query.getId();
        }else {
            userId = user.getId();
        }

        HashMap<String, String> payload = new HashMap<>();
        payload.put("uid",String.valueOf(userId));
        String token = JwtUtis.createJwtStr(payload, 7, TimeUnit.DAYS);

        return token;
    }

    @Override
    public User getUserInfo(String token) {
        try {
            DecodedJWT decodedJWT = JwtUtis.parseJwt(token);
            Claim claim = decodedJWT.getClaim("uid");
            String uid = claim.asString();

            return userMapper.selectById(Long.valueOf(uid));

        }catch (JWTVerificationException e){
        }
        return null;
    }

    @Override
    public void setUserInfo(String token, String name) throws ServiceException {
        Long uid;
        try {
            DecodedJWT decodedJWT = JwtUtis.parseJwt(token);
            Claim claim = decodedJWT.getClaim("uid");
           uid = Long.valueOf( claim.asString());
        }catch (JWTVerificationException e){
            throw new ServiceException("token无效或已过期",e);
        }


        User user = new User();
        user.setName(name);
        QueryWrapper<User> wrapper = new QueryWrapper<>(user);

        User userList = userMapper.selectOne(wrapper);

        if(!ObjectUtils.isEmpty(userList)){
            throw new ServiceException("name ( "+name+" ) 已存在");
        }

        user.setId(uid);
        userMapper.updateById(user);
    }
}
